import React, { useState, useCallback, useEffect } from 'react';
import {
    postLsMealDishesFindLsMealDishes,
    getLsMealDishesRelease,
    getLsMealDishesDeleteLsMealDishes,
    getLsMealDishesGetSystemEnv,
    postLsMealDishesSetSystemEnv
} from '../../api';
import { enumMealTypeArr } from '../../enum';
import SeleceModule from './components/SeleceModule'
import AddMealTypeModule from './components/AddMealTypeModule'
import { SetMealListAll } from './style'
import { PageHeader, Button, message, Table, Space, Modal, Row, Col, TimePicker } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons';
import moment from 'moment';

/**
 * @description: 设置菜品列表页面，
 * @author: xiaoxujs
 * @updata: xiaoxujs（2021-09-03）添加报餐取消截止时间设置
 */

const { confirm } = Modal;

const SetMealList = () => {
    const [listData, setListData] = useState([])
    const [paging, setPaging] = useState({
        currentPage: 1,
        size: 10,
        total: 0
    })
    const [addMealTypeModuleShow, setAddMealTypeModuleShow] = useState(false);
    const [selectData, setSelectData] = useState({});
    const [clickID, setClickID] = useState(undefined);
    const [zaoTime, setZaoTime] = useState('00:00:00');
    const [zhongTime, setZhongTime] = useState('00:00:00');
    const [wanTime, setWanTime] = useState('00:00:00');
    const [zaoStopTime, setZaoStopTime] = useState('00:00:00');
    const [zhongStopTime, setZhongStopTime] = useState('00:00:00');
    const [wanStopTime, setWanStopTime] = useState('00:00:00');
    const listFun = useCallback(
        (parames = {
            currentPage: 1,
            size: 10,
        }) => {
            ; (async () => {
                const { code, msg, data } = await postLsMealDishesFindLsMealDishes(parames)
                if (code === '20000') {
                    setListData(data.records)
                    setPaging({
                        currentPage: parames.currentPage,
                        size: parames.size,
                        total: data.total
                    })
                } else {
                    message.error(msg)
                }
            })()
        },
        [],
    )
    const tiemData = useCallback(
        () => {
            ; (async () => {
                const { code, msg, data } = await getLsMealDishesGetSystemEnv();
                if (code === '20000') {
                    setZaoTime(data.breakfastStop)
                    setZhongTime(data.lunchStop)
                    setWanTime(data.dinnerStop)
                    setZaoStopTime(data.breakfastCancelStop)
                    setZhongStopTime(data.lunchCancelStop)
                    setWanStopTime(data.dinnerCancelStop)
                    // data.forEach(element => {
                    //     if(element.mealType === 0 && element.time) {
                    //         setZaoTime(element.time)
                    //     }
                    //     if(element.mealType === 1 && element.time) {
                    //         setZhongTime(element.time)
                    //     }
                    //     if(element.mealType === 2 && element.time) {
                    //         setWanTime(element.time)
                    //     }
                    // });
                } else {
                    message.error(msg)
                }
            })()
        },
        [],
    )
    useEffect(() => {
        listFun()
        tiemData()
    }, [listFun, tiemData])
    //添加菜品
    const handleAddMeal = () => {
        setAddMealTypeModuleShow(true)

    }
    //发布菜品
    const handleRelease = id => {
        confirm({
            title: '确定要发布当前菜品吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                ; (async () => {
                    const { code, msg } = await getLsMealDishesRelease({ id });
                    if (code === '20000') {
                        message.success('发布成功！');
                        const parames = {
                            currentPage: paging.currentPage,
                            size: paging.size,
                            ...selectData
                        }
                        listFun(parames)
                    } else {
                        message.error(msg);
                    }
                })()
            }
        });
    }
    //编辑
    const handleChangeMeal = id => {
        setClickID(id);
        setAddMealTypeModuleShow(true)
    }
    //删除
    const handleDelete = id => {
        confirm({
            title: '确定要删除当前菜品吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {

                ; (async () => {
                    const { code, msg } = await getLsMealDishesDeleteLsMealDishes({ id });
                    if (code === '20000') {
                        message.success('删除成功！');
                        const parames = {
                            currentPage: paging.currentPage,
                            size: paging.size,
                            ...selectData
                        }
                        listFun(parames)
                    } else {
                        message.error(msg);
                    }
                })()
            }
        });

    }

    //分页
    const pagination = {
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${paging.total}条`,
        //每页条数
        pageSize: paging.size,
        //当前页数
        current: paging.currentPage,
        //数据总数
        total: paging.total,
        //pageSize 变化的回调
        onShowSizeChange: (current, pageSize) => changePageSize(pageSize, current),
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current) => changePage(current),
    }
    //改变每页条数
    const changePageSize = (pageSizeFun, current) => {
        const parames = {
            currentPage: current,
            size: pageSizeFun,
            ...selectData
        }
        listFun(parames);
    }
    //改变页数
    const changePage = (current) => {
        const parames = {
            currentPage: current,
            size: paging.size,
            ...selectData
        }
        listFun(parames);
    }
    //早餐设置
    const handleZaoTime = (time, timeString) => {
        setZaoTime(timeString)
    }
    const handleStopZaoTime = (time, timeString) => {
        setZaoStopTime(timeString)
    }
    //中餐设置
    const handleZhongTime = (time, timeString) => {
        setZhongTime(timeString)
    }
    const handleStopZhongTime = (time, timeString) => {
        setZhongStopTime(timeString)
    }
    //晚餐设置
    const handleWanTime = (time, timeString) => {
        setWanTime(timeString)
    }
    const handleStopWanTime = (time, timeString) => {
        setWanStopTime(timeString)
    }
    //设置时间
    const handleSetTime = (type) => {
        // const parames = [
        //     {
        //         mealType: 0,
        //         time: zaoTime
        //     },
        //     {
        //         mealType: 1,
        //         time: zhongTime
        //     },
        //     {
        //         mealType: 2,
        //         time: wanTime
        //     }
        // ]
        let parames = {}
        if (type === 'stop') {
            parames = {
                breakfastCancelStop: zaoStopTime,
                lunchCancelStop: zhongStopTime,
                dinnerCancelStop: wanStopTime
            }
        } else if (type === 'start') {
            parames = {
                breakfastStop: zaoTime,
                lunchStop: zhongTime,
                dinnerStop: wanTime
            }
        }
        confirm({
            title: '确定要设置时间吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                ; (async () => {
                    const { code, msg } = await postLsMealDishesSetSystemEnv(parames);
                    if (code === '20000') {
                        message.success('设置成功！');
                    } else {
                        message.error(msg)
                    }
                })()
            }
        });
    }
    const columns = [
        {
            title: '报餐名称',
            dataIndex: 'dishes'
        },
        {
            title: '类型',
            dataIndex: 'mealType',
            render: text => <span>{enumMealTypeArr[text]}</span>
        },
        {
            title: '单价',
            dataIndex: 'price'
        },
        {
            title: '供应日期',
            dataIndex: 'supplyDate'
        },
        {
            title: '总数量',
            dataIndex: 'inventory'
        },
        {
            title: '已报份数',
            dataIndex: 'submitted'
        },
        {
            title: '剩余份数',
            dataIndex: 'surplus'
        },
        {
            title: '操作',
            render: (text, recode) => <Space>
                {
                    !recode.state ?
                        <>
                            <Button type="primary" onClick={() => handleRelease(recode.id)}>发布</Button>
                            <Button type="primary" onClick={() => handleChangeMeal(recode.id)}>编辑</Button>
                            <Button type="primary" onClick={() => handleDelete(recode.id)} danger>删除</Button>
                        </>
                        : null
                }

            </Space>
        }
    ];
    return <SetMealListAll>
        <PageHeader
            className="site-page-header"
            title="菜品设置"
            extra={[
                <Button
                    key="1"
                    type="primary"
                    onClick={() => handleAddMeal()}
                >
                    添加菜品
                </Button>,
            ]}
        />
        <SeleceModule
            listFun={listFun}
            setSelectData={setSelectData}
        />
        {/* 报餐截止时间 */}
        <Row className="row_time">
            <Col span={6}>
                早: <TimePicker onChange={handleZaoTime} value={moment(zaoTime, 'HH:mm:ss')} />
            </Col>
            <Col span={6}>中: <TimePicker onChange={handleZhongTime} value={moment(zhongTime, 'HH:mm:ss')} /></Col>
            <Col span={6}>晚: <TimePicker onChange={handleWanTime} value={moment(wanTime, 'HH:mm:ss')} /></Col>
            <Col span={6}>
                <Button type='primary' onClick={() => handleSetTime('start')}> 设置报餐截止时间</Button>
            </Col>
        </Row>
        {/* 报餐取消截止时间 */}
        <Row className="row_time">
            <Col span={6}>
                早: <TimePicker onChange={handleStopZaoTime} value={moment(zaoStopTime, 'HH:mm:ss')} />
            </Col>
            <Col span={6}>中: <TimePicker onChange={handleStopZhongTime} value={moment(zhongStopTime, 'HH:mm:ss')} /></Col>
            <Col span={6}>晚: <TimePicker onChange={handleStopWanTime} value={moment(wanStopTime, 'HH:mm:ss')} /></Col>
            <Col span={6}>
                <Button type='primary' onClick={() => handleSetTime('stop')}> 设置报餐取消截止时间</Button>
            </Col>
        </Row>
        <Table
            dataSource={listData}
            columns={columns}
            pagination={pagination}
            rowKey="id"
        />
        <AddMealTypeModule
            setAddMealTypeModuleShow={setAddMealTypeModuleShow}
            addMealTypeModuleShow={addMealTypeModuleShow}
            listFun={listFun}
            clickID={clickID}
            setClickID={setClickID}
        />
    </SetMealListAll>
}

export default SetMealList